package com.party.admin.biz.crowdfund;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.party.admin.biz.file.ExcelExportService;
import com.party.admin.redisPubSub.publish.RedisMsgPublish;
import com.party.admin.redisPubSub.subscribe.SubScribeMessage;
import com.party.admin.utils.RealmUtils;
import com.party.admin.utils.excel.ExportExcel;
import com.party.common.constant.Constant;
import com.party.common.redis.StringJedis;
import com.party.common.utils.DateUtils;
import com.party.common.utils.LangUtils;
import com.party.core.model.crowdfund.CrowdfundEvent;
import com.party.core.model.member.MerchantUtil;
import com.party.core.service.crowdfund.ICrowdfundEventService;
import com.party.core.service.order.IOrderFormService;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Nullable;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @ClassName CrowdfundEventBizService
 * @Description 主题业务处理
 * @Author yifeng
 * @Date 2019/1/21 16:34
 **/
@Service
public class CrowdfundEventBizService {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private IOrderFormService orderFormService;
    @Autowired
    private RedisMsgPublish redisMsgPublish;
    @Autowired
    private ICrowdfundEventService crowdfundEventService;
    @Autowired
    private ExcelExportService excelExportService;
    @Autowired
    private StringJedis stringJedis;

    /**
     * @param eventId 主题id
     * @Author yifeng
     * @Description 导出主题下的众筹数据及对应商户数据
     * @Date 17:02 2019/1/21
     **/
    public void exportMerchantData(String eventId, String sessionId) {
        CrowdfundEvent crowdfundEvent = crowdfundEventService.get(eventId);
        try {
            // 主题的订单下对应的商户 id和name
            List<Map<String, Object>> merchantLists = orderFormService.distinctMerchantId(eventId);
            if (merchantLists.size() == 0) {
                Map<String, Object> map = Maps.newHashMap();
                map.put("merchantId", MerchantUtil.TXZ_WWZ_MERCHANT_SSFW_ID);
                map.put("merchantName", MerchantUtil.TXZ_WWZ_MERCHANT_SSFW_NAME);
                merchantLists.add(map);
            }
            List<String> merchantIds = LangUtils.transform(merchantLists, new Function<Map<String, Object>, String>() {
                @Nullable
                @Override
                public String apply(@Nullable Map<String, Object> input) {
                    return input.get("merchantId").toString();
                }
            });

            // 商户信息map key是商户id，value是商户名称
            Map<String, String> merchantMap = Maps.newHashMap();
            for (Map<String, Object> data : merchantLists) {
                String merchantId = data.get("merchantId").toString();
                String merchantName = data.get("merchantName").toString();
                merchantMap.put(merchantId, merchantName);
            }

            // 查询主题下众筹成功的人员信息和已筹金额对应的商户
            Map<String, Object> params = Maps.newHashMap();
            params.put("eventId", eventId);
            params.put("merchantIds", merchantIds);
            params.put("isSuccess", Constant.IS_CROWFUND_SUCCESS);
            List<Map<String, Object>> mapList = orderFormService.queryMerchantDatas(params);

            SXSSFWorkbook sxssfWorkbook = this.exportExcel(mapList, merchantMap);


            String fileName = crowdfundEvent.getName() + "众筹成功人员的进账明细.xlsx";
            String allPath = excelExportService.getExcelPath(fileName, "orderform", new ExportExcel(), sxssfWorkbook);
            logger.info("上传成功路径：{}", allPath);
            Map<String, Object> map = Maps.newHashMap();
            map.put("sourceUrl", allPath);
            map.put("uploadTime", DateUtils.formatDate(new Date(), DateUtils.DATETIME_PATTERN));

            stringJedis.setValue(Constant.PRE_ZIP_URL + "event_success_" + eventId, JSONObject.toJSONString(map));

            Map<String, String> json = Maps.newHashMap();
            json.put("memberId", RealmUtils.getCurrentUser().getId());
            json.put("sessionId", sessionId);
            json.put("message", crowdfundEvent.getName() + "成功人员进账明细导出成功了");
            String param = JSONUtils.toJSONString(json);
            redisMsgPublish.publish(SubScribeMessage.CROWDFUND_EXPORT_CHANNEL_NAME, param);
        } catch (Exception e) {
            logger.error("导出异常", e);
            Map<String, String> json = Maps.newHashMap();
            json.put("memberId", RealmUtils.getCurrentUser().getId());
            json.put("sessionId", sessionId);
            json.put("message", crowdfundEvent.getName() + "成功人员进账明细导出异常了");
            String param = JSONUtils.toJSONString(json);
            redisMsgPublish.publish(SubScribeMessage.CROWDFUND_EXPORT_CHANNEL_NAME, param);
        }
    }

    /**
     * 导出Excel
     *
     * @param projects 表单信息
     * @return excel公众薄
     */
    public SXSSFWorkbook exportExcel(List<Map<String, Object>> projects, Map<String, String> merchantMap) {
        SXSSFWorkbook wb = new SXSSFWorkbook();
        Sheet sheet0 = wb.createSheet("众筹成功的数据");

        String[] titles = {
                "昵称", "公司", "手机号", "目标金额", "已筹金额"
        };

        // 标题
        Row titleRow = sheet0.createRow(0);
        for (int i = 0; i < titles.length; i++) {
            Cell cell = titleRow.createCell(i);
            cell.setCellValue(titles[i]);
        }

        int i = 0;
        for (Map.Entry<String, String> entry : merchantMap.entrySet()) {
            Cell cell = titleRow.createCell(titles.length + i);
            cell.setCellValue(entry.getValue());
            i++;
        }

        List<Object> values = Lists.newArrayList();

        for (int j = 0; j < projects.size(); j++) {
            Map<String, Object> objectMap = projects.get(j);

            // 昵称
            Object realname = objectMap.get("realname");
            // 公司名称
            Object company = objectMap.get("company");
            // 手机号
            Object mobile = objectMap.get("mobile");
            // 目标金额
            Object targetAmount = objectMap.get("targetAmount");
            // 已筹金额
            Object actualAmount = objectMap.get("actualAmount");


            values.clear();
            values.add(realname);
            values.add(company);
            values.add(mobile);
            values.add(targetAmount);
            values.add(actualAmount);

            Row dataRow = sheet0.createRow(j + 1);

            for (int k = 0; k < values.size(); k++) {
                Cell dataCell = dataRow.createCell(k);

                if (null != values.get(k)) {
                    if (values.get(k) instanceof Float) {
                        dataCell.setCellValue(Float.valueOf(values.get(k).toString()));
                    } else {
                        dataCell.setCellValue(values.get(k).toString());
                    }
                } else {
                    dataCell.setCellValue("");
                }
            }


            int k = 0;

            for (Map.Entry<String, String> entry : merchantMap.entrySet()) {
                // 商户对应的金额
                Object o = objectMap.get(entry.getKey());

                Cell dataCell = dataRow.createCell(values.size() + k);
                dataCell.setCellValue(Double.valueOf(o.toString()));
                k++;
            }
        }
        return wb;
    }
}
